package com.krm.codemanager.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import utils.Result;

import com.alibaba.fastjson.JSONArray;
import com.beaf.organization.po.BeafUsers;
import com.krm.codemanager.model.CategoryMaintain;
import com.krm.codemanager.service.CategoryService;

/**
 * 
 * @author yangyuanshuai
 * 
 */
@Controller
@RequestMapping("codemanager/category")
public class CategoryController extends BaseController {
	@Resource
	CategoryService categoryServic;

	@RequestMapping
	public String enter(Integer Jurisdiction) {
		if(Jurisdiction == 1){
			logger.info("跳转到建表记录页面category-list");
			return "/WEB-INF/jsp/category/category-list.jsp";			
		}else if(Jurisdiction == 2){
			logger.info("跳转到建表记录页面category-list2");
			return "/WEB-INF/jsp/category/category-list2.jsp";
		}
		return null;
	}

	@RequestMapping(value = "toAddOrUpdate")
	public Object addOrUpdateLayer(String type, Model model, Integer stdCatId) {
		if (type.equals("add")) {
			model.addAttribute("type", "add");
		} else {
			List<CategoryMaintain> list = categoryServic
					.entityList(new HashMap<String, Object>());
			for (CategoryMaintain categoryMaintain : list) {
				if (categoryMaintain.getStdCatId().equals(stdCatId)) {
					model.addAttribute("category", categoryMaintain);
					break;
				}
			}
			model.addAttribute("type", "update");
		}
		return "/WEB-INF/jsp/category/category-addOrUpdate.jsp";
	}

	@RequestMapping(value = "list", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public Object categorytist(@RequestParam Map<String, Object> params) {
		return JSONArray.toJSON(categoryServic.queryPageInfo(params));
	}

	@RequestMapping(value = "saveOrEdit", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public Object save(CategoryMaintain categoryMaintain, String type,
			@ModelAttribute("params") Map<String, Object> params,Model model) {
		int count = 0;
		if (type.equals("add")) {
			String  username = ((BeafUsers)params.get("user")).getUserName();
			categoryMaintain.setCreatorName(username);
			String time = new Timestamp(new Date().getTime()).toString();
			categoryMaintain.setCreateTime(time);
			String stdCatType = params.get("stdCatType").toString();
			CategoryMaintain onlyone = this.onlyone(type, model, stdCatType);
			if(onlyone!=null){
				return Result.errorResult1();
			}else{
				count = categoryServic.addCategory(categoryMaintain);
			}
		} else {
			String  username = ((BeafUsers)params.get("user")).getUserName();
			categoryMaintain.setMaintainerName(username);
			String time = new Timestamp(new Date().getTime()).toString();
			categoryMaintain.setModefyTime(time);
			count = categoryServic.updateCategory(categoryMaintain);
		}
		if (count > 0) {
			return Result.successResult();
		} else {
			return Result.errorResult();
		}
	}

	// @RequestMapping(value = "edit", method = RequestMethod.POST)
	// @ResponseBody
	// public Object edit(CategoryMaintain categoryMaintain) {
	// int count = categoryServic.updateCategory(categoryMaintain);
	// if (count > 0) {
	// return Result.successResult();
	// } else {
	// return Result.errorResult();
	// }
	// }

	@RequestMapping(value = "del", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public Object del(String stdCatId) {
		Integer count = 0;
		for (String string : stdCatId.split(",")) {
			count += categoryServic.delCategory(Integer.parseInt(string));
		}
		if (count.equals(stdCatId.split(",").length)) {
			return Result.successResult();
		} else {
			return Result.errorResult();
		}
	}

	/**
	 * 数据导入
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "importexcel", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public Result importFile(@RequestParam("file") MultipartFile fileList[],
			HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		if (file.isEmpty()) {
			throw new Exception("文件不存在!");
		}
		InputStream in = file.getInputStream();
		try {
			// 导出Excel对象
			String msg = categoryServic.uploadPayerCreditInfoExcel(in, file);
			return Result.successResult1(msg);
		} catch (Exception e1) {
			e1.printStackTrace();
			return Result.errorResult("文件导入失败!");

		}
		finally{
			in.close();
		}

	}

	/**
	 * 导出excel
	 * 
	 * @return
	 */
	@RequestMapping(value = "excelexport", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void export(@ModelAttribute("params") Map<String, Object> params,
			HttpServletResponse response,HttpServletRequest request) {
		if (params.get("exportType") == null) {
		} else {
		}
		response.reset();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
		String dateStr = "类别维护"+sdf.format(new Date());
		Map<String, Object> map = new HashMap<String, Object>();
		// 指定下载的文件名
		try {
			response.setHeader("Content-Disposition", "attachment;filename="
					+  new String(dateStr.getBytes(), "ISO-8859-1") + ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		XSSFWorkbook workbook = null;
		try {
			// 导出Excel对象
			String  username = ((BeafUsers)params.get("user")).getUserName();
			workbook = categoryServic.exportPayerCreditInfoExcel(username);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		}
		OutputStream output;
		try {
			output = response.getOutputStream();

			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			workbook.write(bufferedOutPut);
			bufferedOutPut.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 下载模版
	 * 
	 * @return
	 */
	@RequestMapping(value = "downloadTemplete", method = { RequestMethod.POST,
			RequestMethod.GET })
	public Result downloadTemplete(HttpServletResponse response) {
		// 获取查询数据，在service层实现
		XSSFWorkbook wb = new XSSFWorkbook();// 声明工
		Sheet sheet = wb.createSheet("类别维护");// 新建表
		sheet.setDefaultColumnWidth(15);// 设置表宽
		XSSFCellStyle style = wb.createCellStyle();
		XSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 12);
		XSSFCellStyle headerStyle = wb.createCellStyle();
		XSSFFont headerFont = wb.createFont();
		headerFont.setFontHeightInPoints((short) 14);
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		headerStyle.setFont(headerFont);
		sheet.setDefaultColumnWidth((short) 15);
		Row row1 = sheet.createRow(0);
		Cell cell = row1.createCell(0);
		cell.setCellValue("代码类别");
		cell.setCellStyle(style);
		cell = row1.createCell(1);
		cell.setCellValue("类别名称");
		cell.setCellStyle(style);
		cell = row1.createCell(2);
		cell.setCellValue("创建时间");
		cell.setCellStyle(style);
		cell = row1.createCell(3);
		cell.setCellValue("修改时间");
		cell.setCellStyle(style);
		cell = row1.createCell(4);
		cell.setCellValue("创建人");
		cell.setCellStyle(style);
		cell = row1.createCell(5);
		cell.setCellValue("维护人");
		cell.setCellStyle(style);
		//Row row11 = sheet.createRow(1);
		// 时间转字符串的格式
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
		String dateStr = "类别维护模板";/* + sdf.format(new Date());*/
		response.reset();
		try {
			response.setHeader("Content-Disposition", "attachment;filename="
					+  new String(dateStr.getBytes(), "ISO-8859-1") + ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		OutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			wb.write(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	
	@RequestMapping(value = "onlyone", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public CategoryMaintain onlyone(String type, Model model, String stdCatType){
		CategoryMaintain categoryMaintain = new CategoryMaintain();
		categoryMaintain.setStdCatType(stdCatType);
		CategoryMaintain result = categoryServic.getOnlyone(categoryMaintain);
		return result;
		
	}

}
